<script setup lang="ts">
import XtxCheckbox from "@/components/XtxCheckbox.vue";
import * as zod from "zod";
import { Field, ErrorMessage } from "vee-validate";
import { toFormValidator } from "@vee-validate/zod";
import { useUserStore } from "@/stores/userStore";
import { AuthAPI } from "@/api/AuthAPI";
const userStore = useUserStore();
// 将 zod 的验证格式转换为 vee-validate 支持的验证格式
const validator = toFormValidator(
  // 定义表单的验证规则
  zod.object({
    account: zod
      .string({
        required_error: "请输入用户名",
        invalid_type_error: "用户名类型错误",
      })
      .regex(/^[a-zA-Z]\w{5,19}$/, "用户名的长度必须是6-20位"),
    password: zod
      .string({
        required_error: "请输入密码",
        invalid_type_error: "密码类型错误",
      })
      .regex(/^\w{6,24}$/, "密码的长度必须是6-24位"),
    isAgree: zod.literal(true, { errorMap: () => ({ message: "请勾选协议" }) }),
  })
);

// 创建验证表单对象
const { handleSubmit, values, setFieldValue, validateField } = useForm({
  validationSchema: validator,
  initialValues: {
    account: "",
    password: "",
    isAgree: false,
  },
});

// 表单提交
const onSubmit = handleSubmit((formValues) => {
  // 发送登录请求
  userStore.login(() =>
    AuthAPI.loginByAccount(formValues.account, formValues.password)
  );
});
</script>

<template>
  <form @submit="onSubmit">
    <Field name="account" class="form-item" as="div" v-slot="{ field }">
      <div class="input">
        <i class="iconfont icon-user"></i>
        <input v-bind="field" type="text" placeholder="请输入用户名" />
      </div>
      <ErrorMessage name="account" v-slot="{ message }">
        <div class="error">
          <i class="iconfont icon-warning"></i> {{ message }}
        </div>
      </ErrorMessage>
    </Field>
    <Field name="password" class="form-item" as="div" v-slot="{ field }">
      <div class="input">
        <i class="iconfont icon-lock"></i>
        <input
          v-bind="field"
          autocomplete="on"
          type="password"
          placeholder="请输入密码"
        />
      </div>
      <ErrorMessage name="password" v-slot="{ message }">
        <div class="error">
          <i class="iconfont icon-warning"></i> {{ message }}
        </div>
      </ErrorMessage>
    </Field>
    <Field class="form-item" name="isAgree" as="div">
      <div class="agree">
        <XtxCheckbox
          :checked="values.isAgree"
          @onChanged="
            setFieldValue('isAgree', $event);
            validateField('isAgree');
          "
        />
        <span>我已同意</span>
        <a href="javascript:">《隐私条款》</a>
        <span>和</span>
        <a href="javascript:">《服务条款》</a>
      </div>
      <ErrorMessage name="isAgree" v-slot="{ message }">
        <div class="error">
          <i class="iconfont icon-warning"></i> {{ message }}
        </div>
      </ErrorMessage>
    </Field>
    <button type="submit" class="btn">登录</button>
  </form>
</template>
